<?php

namespace app\controller;

use support\Request;
use Kingbes\Attribute\Annotation;
use Webman\Captcha\CaptchaBuilder;
use app\model\Admins;

#[Annotation(title: "登记")]
class LoginController
{
    #[Annotation(title: "登记", view: true)]
    public function index(Request $request)
    {
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $all = $request->all();
            // 验证
            if (strtolower($all["captcha"]) !== $request->session()->get('captcha')) {
                return error("验证码不正确");
            }
            $find = Admins::where("username", $all["username"])
                ->withJoin(['role' => ['role.name' => 'role', "role.rules" => "rules"]], 'left')
                ->find();
            if (!$find) {
                return error("请输入正确的账号");
            }
            if (!password_verify($all["password"], $find["password"])) {
                return error("请输入正确的密码");
            }
            if ($find->status != "正常" && $find->id != 1) {
                return error("该账号已被禁用");
            }
            // 保存
            $find->save(["login_time" => time()]);
            // 登录
            session(['Admin' => $find]);
            return success("登录成功", route("admin.index.index"));
        }
        // 渲染模板
        return fetch();
    }

    #[Annotation(title: "验证")]
    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    #[Annotation(title: "退出")]
    public function logout(Request $request)
    {
        // 清除session
        $request->session()->delete('Admin');
        return success("退出成功", route("admin.login.index"));
    }
}
